#!/usr/bin/env python
# -*- coding: utf-8 -*

""" RTorrent client 

Invented and implemented by Marek Pułczyński (marek@pulczynski.com) (2007) """

import socket
socket.setdefaulttimeout(15)
from optparse import OptionParser

import logging
from application import RTorrentApplication
from settings import FORMAT_CONS, FORMAT_FILE
if __name__ == '__builtin__' or __name__ == "__main__":
    log_str_help = ','.join(["%d=%s" % (4-x, logging.getLevelName((x+1)*10)) for x in xrange(5)])

    parser = OptionParser(usage="%prog --root PATH --port PORT",
                         description = "Web rtorrent client",
                         version="webrtorrent: %prog daemon by marek@pulczynski.com (2007) ")
    parser.add_option("-p", "--port",                        dest="port",        type = "int",     default=3095, help="port to listen on [default: %default]")
    parser.add_option("-v",             action="count",      dest="verbosity",         default = 0, help = "Verbosity. Add more -v to be more verbose (%s) [default: %%default]" % log_str_help)
    parser.add_option("-l", "--logfile",dest="logfile",    default = None, help = "Log to file instead off console [default: %default]" )

    (options, args) = parser.parse_args()

    # options check
    if not options.port:
        parser.error("No port supplied! Specify root path using --port=$PORT option!")

    # sanitize options
    verbosity = 5-int(options.verbosity)
    port = int(options.port)

    if not (0 < port < 66535):
        parser.error("Port must be in useful range (1-65535)!")

    if options.logfile is None:
        logging.basicConfig(level=(verbosity)*10, format=FORMAT_CONS) #%(lineno)d
    else:
        # log to file
        logfilename = os.path.normpath(options.logfile)
        logging.basicConfig(level=(verbosity)*10, format=FORMAT_FILE, filename=logfilename, filemode='a')
        print "Logging to %s" % logfilename

    log = logging.getLogger('webrtorrent')
    log.debug("Running with verbosity %d (>=%s)" % (verbosity, logging.getLevelName(verbosity*10)))

    from twisted.internet import reactor
    reactor.suggestThreadPoolSize(32)
    from twisted.web2 import wsgi, channel,server
    from twisted.web2 import log as twisted_log
    from twisted.python import log as tlog
    import sys
    tlog.startLogging(sys.stdout)

    ###  Real program start ######################
    main_resource = wsgi.WSGIResource(RTorrentApplication)
    # Setup default common access logging
    logging_resource = twisted_log.LogWrapperResource(main_resource)
    twisted_log.DefaultCommonAccessLoggingObserver().start()
    reactor.listenTCP(port, channel.HTTPFactory(server.Site(logging_resource)))
    log.info("Running webrtorrent on 0.0.0.0:%d", port)
    reactor.run()

    log.info("Storaged stopped")
